import { queryCurrentTenant, listInAuth } from '@/api/tenant'
import { login, logout } from '@/api/auth'
import { setCacheTenant, setToken, removeToken, clearCacheTenant } from '@/utils/auth'
import { clearCacheRouter } from '@/utils/menu'
import message from '@/store/modules/message'

const getDefaultState = () => {
  return {
    avatar: ""
  }
}

const state = getDefaultState()

const mutations = {

}

const actions = {
  /**
   * 登录
   */
  login({ commit }, loginForm) {
    return new Promise((resolve, reject) => {
      login(loginForm).then(res => {
        // oauth2鉴权，需要加上type(标识鉴权模式),一定有空格
        const token = `${res.data.type} ${res.data.token}`;
        setToken(token);
        resolve(res);
      }).catch((err) => {
        reject(err);
      });
    })
  },
  /**
   * 登出
   */
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      logout().then(res => {
        removeToken();
        clearCacheTenant();
        clearCacheRouter();
        resolve(res);
      }).catch((err) => {
        reject(err);
      });
    })
  },
  /**
   * 获取当前租户
   */
  getCurrentTenant() {
    return new Promise((resolve, reject) => {
      queryCurrentTenant().then(res => {
        // 存储当前租户进session中
        if (res.code === 0) {
          setCacheTenant(res.data);
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  /**
   * 查询下级租户列表
   */
  listInAuth({ commit }, searParams) {
    return new Promise((resolve, reject) => {
      listInAuth(searParams).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
